const userRepository = require('../repositories/user.repositories');

class UserService {
    async getAllUsers() {
        const users = await userRepository.findAllUsers();
        return users;
    }

    async getUserById(id) {
        const user = await userRepository.findUserById(id);
        if (!user) {
            throw new Error('用户不存在');
        }
        return user;
    }

    async createUser(userData) {
        // 业务逻辑验证
        if (!userData.name || !userData.email) {
            throw new Error('用户名和邮箱不能为空');
        }
        
        // 检查邮箱是否已存在
        const existingUser = await userRepository.query(
            'SELECT * FROM users WHERE email = ?', 
            [userData.email]
        );
        
        if (existingUser.length > 0) {
            throw new Error('邮箱已存在');
        }
        
        const result = await userRepository.createUser(userData);
        return result;
    }

    async updateUser(id, userData) {
        const user = await userRepository.findUserById(id);
        if (!user) {
            throw new Error('用户不存在');
        }
        
        return await userRepository.updateUser(id, userData);
    }

    async deleteUser(id) {
        const user = await userRepository.findUserById(id);
        if (!user) {
            throw new Error('用户不存在');
        }
        
        return await userRepository.deleteUser(id);
    }
}

module.exports = new UserService();